package day30.edu;

import org.junit.Test;

import java.io.*;

// Created: 30/09/2025, ChangJiang Ru
public class FileReaderWriterTest {
    @Test
    public void test1() {
        FileReader fileReader = null;
        try {
            File file = new File("hello.txt");

            fileReader = new FileReader(file);

            // Read the data, and expression in the console
            // Case 1:
        /*
        int data = fileReader.read();
        while(data != -1)
        {
            System.out.print((char)data);
            data = fileReader.read();
        }
        */

            // Case 2:
            /*
            int data;
            while((data = fileReader.read()) != -1)
            {
                System.out.print((char)data);
            }
             */
            char[] charBuffer = new char[5];
            int len;
            while ((len = fileReader.read(charBuffer)) != -1) {
                for (int i = 0; i < len; i++) {
                    System.out.println(charBuffer[i]);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // Stream must be closed
            try {
                fileReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    @Test
    public void test2() {
        FileWriter fileWriter = null;
        try {
            // Create file object
            File file = new File("info.txt");

            // Create output stream
            fileWriter = new FileWriter(file);

            // Writer the local process
            fileWriter.write("I love you!\n");
            fileWriter.write("i love you too \n");

            System.out.println("Print successfully");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // Close the source
            try {
                if (fileWriter != null)
                    fileWriter.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

}
